/**
*  Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
*/
package cn.knet.sp.ncrm.modules.call.record.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.CrudService;
import cn.knet.sp.ncrm.common.utils.DateUtils;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.modules.call.record.dao.RecordInfoDao;
import cn.knet.sp.ncrm.modules.call.record.entity.RecordInfo;
import cn.knet.sp.ncrm.modules.call.record.entity.RecordInfoQuery;

/**
 * TODO(这里用一句话描述这个类的作用)
 * @author Gehaiyangs
 * @date 2015年6月29日 下午4:07:18
 * 
 */
@Service
public class RecordInfoService extends CrudService<RecordInfoDao, RecordInfo> {

	public static final String TABLE_NAME = "T_RECORD_INFO";
	
	/**
	 *  TODO(列表查询)
	 * @author Gehaiyang
	 * @date 2015年7月2日 上午9:43:09
	 * @param page
	 * @param entity
	 * @return
	 */
	public Page<RecordInfo> findPage(Page<RecordInfo> page, RecordInfoQuery entity){
		Date beginDate = null;
		Date endDate = null;
		Date nowDate = new Date();
		if(StringUtils.isNotBlank(entity.getBeginDateTime())) {
			beginDate = DateUtils.parseDate(entity.getBeginDateTime());
		} else {
			beginDate = nowDate;
		}
		if(StringUtils.isNotBlank(entity.getEndDateTime())) {
			endDate = DateUtils.parseDate(entity.getEndDateTime());
		} else {
			endDate =  nowDate;
		}
		//需要查询的表
		Set<String> tables = new HashSet<String>();
		if(beginDate.before(endDate) && !isToday(beginDate,endDate)){
			Calendar calendar = Calendar.getInstance(Locale.CHINA);
			calendar.setTime(beginDate);
			int beginMonth = calendar.get(2)+ 1;
			int beginYear = calendar.get(1);
			calendar.setTime(endDate);
			int endMonth = calendar.get(2)+ 1;
			int endYear = calendar.get(1);
			if(beginYear == endYear && beginMonth <= endMonth) {
				while ( beginMonth <= endMonth ) {
					tables.add(TABLE_NAME + "_" + beginMonth);
					beginMonth++;
				}
			} else {
				while ( beginMonth <= 12 ) {
					tables.add(TABLE_NAME + "_" + beginMonth);
					beginMonth++;
				}
				for (int i = 1; i <= endMonth; i++) {
					tables.add(TABLE_NAME + "_" + i);
				}
			}
		}
		entity.setTables(new ArrayList<String>(tables));
		return super.findPage(page, entity);
	}
	/**
	 *  TODO(判断是否当天)
	 * @author Gehaiyang
	 * @date 2015年7月2日 上午9:42:42
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	private boolean isToday(Date beginDate,Date endDate){
		String beginTemp = DateFormatUtils.format(beginDate, "yyyy-MM-dd");
		String endTemp = DateFormatUtils.format(endDate, "yyyy-MM-dd");
		String nowTemp = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
		return beginTemp.equals(nowTemp) && endTemp.equals(nowTemp);
	}
}
